package org.kl.bf.web.basic;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.kl.bf.entity.basic.BasicFile;
import org.kl.bf.entity.easyui.EasyuiGrid;
import org.kl.bf.service.basic.BasicFileService;
import org.kl.bf.utils.BasicConstants;
import org.kl.bf.utils.KLFileUtils;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

/**
 * 
 * @Author hqm
 * @CreateTime 2014-3-13 下午9:34:36
 */
@Controller
@RequestMapping(value = "/basic/basicFile")
public class BasicFileController extends BasicController {

	@Autowired
	private BasicFileService basicFileService;

	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/basicFileList";
	}

	/**
	 * 删除附件
	 * 
	 * @param id
	 * @param redirectAttributes
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "delete/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if (deleteBasicFile(id, request, "删除")) {
			return ajaxMsg("删除成功", true, null);
		} else {
			return ajaxMsg("删除失败", false, null);
		}
	}

	private boolean deleteBasicFile(String id, HttpServletRequest request, String action) {
		BasicFile basicFile = basicFileService.getBasicFile(id);
		// 删除时，同时将文件放入回收站
		try {
			File file = new File(basicFile.getFilePath());
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			File destFile = new File(basicFile.getFilePath().replace("uploadFiles", "recycle") + "_" + df.format(new Date()) + action);
			FileUtils.moveFile(file, destFile);
			basicFileService.deleteBasicFile(id);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@RequestMapping(value = "upload",produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String upload(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		String responseStr = "";
		DecimalFormat df2 = new DecimalFormat("###.00");
		String configFilePath = (String) session.getServletContext().getAttribute(BasicConstants.CONFIG_UPLOADPATH);
		if (StringUtils.isBlank(configFilePath)) {
			configFilePath = "uploadFilePath";
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		String ctxPath;
		try {
			/*
			 * ctxPath = KLFileUtils.getExcelImportFileSavePath(configFilePath,
			 * session.getServletContext().getRealPath("/"));
			 */
			ctxPath = KLFileUtils.getFileSavePath(session.getServletContext().getRealPath("/"));
		} catch (Exception e1) {
			e1.printStackTrace();
			return ajaxMsg("上传路径创建失败", false, null);
		}
		String fileName = null;
		BasicFile basicFile = new BasicFile();
		// String s = multipartRequest.getParameter("joinFileId");
		basicFile.setJoinFileId(multipartRequest.getParameter("joinFileId"));
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 上传文件名
			MultipartFile mf = entity.getValue();
			fileName = mf.getOriginalFilename();
			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			String oldFileName = fileName.substring(0, fileName.lastIndexOf("."));

			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String newFileName = oldFileName + df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
			File uploadFile = new File(ctxPath + newFileName);
			try {
				FileCopyUtils.copy(mf.getBytes(), uploadFile);
				responseStr = "上传成功";
				basicFile.setFileName(fileName);
				basicFile.setFilePath(uploadFile.getAbsolutePath());
				String fileSize = df2.format(uploadFile.length() / 1024);
				basicFile.setFileSize(fileSize);
				basicFile.setUploadTime(new Date());
				basicFile.setUploader(getCurrentUserName());
				basicFile.setFileType(fileExt);
				basicFileService.saveBasicFile(basicFile);
			} catch (IOException e) {
				responseStr = "上传失败";
				e.printStackTrace();
			}
		}
		return ajaxMsg(responseStr, true, basicFile);
	}

	/**
	 * 文件下载
	 * 
	 * @param response
	 * @param request
	 * @param realName
	 * @param name
	 */
	@RequestMapping(value = "download/{attachId}", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	public void download(HttpServletResponse response, HttpServletRequest request, @PathVariable("attachId") String attachId) {
		OutputStream os = null;
		BasicFile basicFile = basicFileService.getBasicFile(attachId);
		basicFile.setDownloader(getCurrentUserName());
		basicFile.setLastDownloadTime(new Date());
		basicFileService.saveBasicFile(basicFile);
		response.reset();
		try {
			response.setHeader("Content-Disposition", "attachment;filename=\""
					+ new String((basicFile.getFileName()).getBytes("gb2312"), "ISO8859-1") + "\"");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		response.setContentType("application/octet-stream; charset=utf-8");
		try {
			os = response.getOutputStream();
			os.write(FileUtils.readFileToByteArray(new File(basicFile.getFilePath())));
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 获取附件列表,通过附件主表Id获取
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
	 * @param orderType
	 * @param model
	 * @param request
	 * @param masterId
	 *            附件主表Id
	 * @return
	 */
	@RequestMapping(value = "dataGrid/{masterId}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			@PathVariable("masterId") String masterId) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		searchParams.put("EQ_basicFileMasterId", masterId);
		Page<BasicFile> basicFiles = basicFileService.getUserBasicFile(searchParams, pageNumber, pageSize, sortType, orderType);
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(basicFiles.getContent());
		grid.setTotal((int) basicFiles.getTotalElements());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	/**
	 * 获取全部附件列表
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
	 * @param orderType
	 * @param model
	 * @param request
	 * @param masterId
	 *            附件主表Id
	 * @return
	 */
	@RequestMapping(value = "showDataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String showDataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<BasicFile> basicFiles = basicFileService.getUserBasicFile(searchParams, pageNumber, pageSize, sortType, orderType);
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(basicFiles.getContent());
		grid.setTotal((int) basicFiles.getTotalElements());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	@RequiresPermissions({ "basicFile:delete" })
	@RequestMapping(value = "multiDelete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = basicFileService.multiDelete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("删除成功:" + msg, true, null);
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getBasicFile(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("basicFile", basicFileService.getBasicFile(id));
		}
	}

}